import argparse, flask, sys, logging, os, time
from datetime import datetime
from logging import handlers
dir = os.path.abspath('..')
sys.path.append(dir)
from main.link.sshLink import sshLink
from main.tools.setHttpOrganization import after_request
from main.thread.sshThread import sshPrintThread
from main.tools.sshStatusThread import sshStatusThread


api = flask.Flask(__name__)
api.after_request(after_request)

# 设置脚本输入参数
parser = argparse.ArgumentParser(description='argparse testing')
parser.add_argument('--ip', '-l', type=str, required=True, help="IPAddress")
parser.add_argument('--port', '-P', type=int, default=22, help='Port')
parser.add_argument('--user', '-u', type=str, default='root', help="Login User")
parser.add_argument('--passwd', '-p', type=str, help="Passwd")
parser.add_argument('--size', '-s', type=int, default='100', help="Size")
parser.add_argument('--timeout', '-t', type=int, default=72000, help="TimeOut")
parser.add_argument('--apiport', '-i', type=int, help="ApiPort")
parser.add_argument('--outport', '-o', type=int, help="OutPort")
args = parser.parse_args()

# 打印日志
logger = logging.getLogger('')
rth = handlers.RotatingFileHandler("./log/serverJaina.log", maxBytes=10 * 1024 * 1024, backupCount=7)
logger.setLevel(logging.INFO)
rth.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(rth)

# 时间格式声明，用于后面的记录系统时间
ISOTIMEFORMAT = '%Y年%m月%d日 %H点%M分%S秒'
sshIP = args.ip
if os.path.exists(r'log/' + sshIP + ''):
    logger.info(sshIP + " 终端日志文件夹已存在，不创建。")
else:
    os.makedirs(r'log/' + sshIP + '')
    logger.info(sshIP + " 终端日志文件夹不存在，已创建。")

# 时间戳为了解决同一时间打开多个终端，日志文件冲突
trandom = time.time()
# trandom = random.randint(1000000,9999999)
with open('log/' + sshIP + '/' + sshIP + '-' + datetime.now().strftime(
        '%Y年%m月%d日').__str__() + '-' + trandom.__str__() + '.txt', mode='a+', encoding='utf-8') as note:
    note.write("\n" + "#############################################################" + "\n")
    note.write("\n" + "会话开始：" + datetime.now().strftime(ISOTIMEFORMAT).__str__() + "\n")
    note.write("\n" + "会话开始时间-" + time.time().__str__() + "\n")
    note.write("\n" + "#############################################################" + "\n")

try:
    sshChannel = sshLink(args.ip, args.port.__str__(), args.user, args.passwd, args.size, args.timeout)
except Exception as e:
    logger.error(e)
    if(e.__str__() == "Authentication failed."):
        thread2 = sshStatusThread("201", args.outport)
        thread2.start()
    else:
        thread2 = sshStatusThread("500", args.outport)
        thread2.start()
else:
    thread2 = sshStatusThread("200", args.outport)
    thread2.start()
    @api.route('/jaina', methods=['post'])
    # 实时命令接口
    def sshSendCmd():
        cmd = flask.request.values.get('cmd')

        sshChannel.set_name(args.ip)
        sshChannel.send(cmd)

        thread2 = sshPrintThread(sshChannel, args.outport, trandom)
        thread2.start()
        # print(sshChannel) #超时控制
        if "active" in sshChannel.__str__() and "0 open" not in sshChannel.__str__() and "1 open" in sshChannel.__str__():
            return "200"
        return "500"
    if __name__ == '__main__':
        # 接口启动时会运行两次 是因为debug功能的开启
        try:
            api.run(port=args.apiport, debug=False, host='127.0.0.1')
        except Exception as e:
            logger.error(e)

